package com.dbflow5.transaction;

import com.dbflow5.config.DBFlowDatabase;
import com.dbflow5.config.FlowLog;
import com.dbflow5.runtime.DBBatchSaveQueue;

/**
 * Description: The base implementation of Transaction manager.
 */
public abstract class BaseTransactionManager {

    ITransactionQueue queue;
    DBFlowDatabase databaseDefinition;

    public BaseTransactionManager(ITransactionQueue queue, DBFlowDatabase databaseDefinition){
        this.queue = queue;
        this.databaseDefinition = databaseDefinition;

        checkQueue();
    }

    private final DBBatchSaveQueue _saveQueue = new DBBatchSaveQueue(databaseDefinition);

    public DBBatchSaveQueue saveQueue(){
        try {
            if (!_saveQueue.isAlive()) {
                _saveQueue.start();
            }
        } catch (IllegalThreadStateException i) {
            FlowLog.logError(i); // if queue is alive, will throw error. might occur in multithreading.
        }

        return _saveQueue;
    }

    /**
     * Checks if queue is running. If not, should be started here.
     */
    public void checkQueue() {
        queue.startIfNotAlive();
    }

    /**
     * Stops the queue this manager contains.
     */
    public void stopQueue() {
        queue.quit();
    }

    /**
     * Adds a transaction to the [ITransactionQueue].
     *
     * @param transaction The transaction to add.
     */
    public void addTransaction(Transaction<?> transaction) {
        queue.add(transaction);
    }

    /**
     * Cancels a transaction on the [ITransactionQueue].
     *
     * @param transaction transaction
     */
    public void cancelTransaction(Transaction<?> transaction) {
        queue.cancel(transaction);
    }
}
